package com.fas.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fas.common.core.domain.AjaxResult;
import com.fas.common.core.domain.entity.SysUser;
import com.fas.common.core.redis.RedisCache;
import com.fas.common.exception.ServiceException;
import com.fas.common.utils.DictUtils;
import com.fas.common.utils.StringUtils;
import com.fas.system.domain.FasInspectionLine;
import com.fas.system.domain.vo.*;
import com.fas.system.mapper.FasFacilitiesMapper;
import com.fas.system.mapper.FasInspectionLineMapper;
import com.fas.system.service.IFasInspectionLineService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FasInspectionLineServiceImpl implements IFasInspectionLineService {

    @Resource
    private FasInspectionLineMapper fasInspectionLineMapper;
    @Resource
    private FasFacilitiesMapper fasFacilitiesMapper;
    @Resource
    private RedisCache redisCache;


    @Override
    public List<FasInspectionLine> queryAll(FasInspectionLine fasInspectionLine) {
        List<FasInspectionLine> list = fasInspectionLineMapper.queryAll(fasInspectionLine);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public FasInspectionLine findById(Long id) {
        return fasInspectionLineMapper.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertFasInspectionLine(FasInspectionLine fasInspectionLine) {
        List<Integer> facilityIds = fasInspectionLine.getFacilityIds();
        if (CollectionUtils.isEmpty(facilityIds)) {
            throw new ServiceException("添加的巡检路线设施不能为空！");
        }
        long lineId = System.currentTimeMillis();
        fasInspectionLine.setId(lineId);
        int count = fasInspectionLineMapper.insertFasInspectionLine(fasInspectionLine);
        if (count > 0) {
            // 设施表中绑定路线
            fasFacilitiesMapper.batchUpdateInspectionLine(facilityIds, lineId);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateFasInspectionLine(FasInspectionLine fasInspectionLine) {
        int count = fasInspectionLineMapper.updateFasInspectionLine(fasInspectionLine);
        if (count > 0) {
            // 设施表中绑定路线
            List<Integer> facilityIds = fasInspectionLine.getFacilityIds();
            if (!CollectionUtils.isEmpty(facilityIds)) {
                // 先将设施表中的线路更新为空，再更新为当前的路线
                Long[] lineId = {fasInspectionLine.getId()};
                fasFacilitiesMapper.batchDeleteRoute(lineId);
                fasFacilitiesMapper.batchUpdateInspectionLine(facilityIds, fasInspectionLine.getId());
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteFasInspectionLine(Long[] ids) {

        List<Long> existsIds = new ArrayList<>();
        List<Long> dataList = new ArrayList<>();
        // 查询路线下是否绑定设施和路线
        if (ids != null && ids.length > 0) {
            for (Long id : ids) {
//                int exists = fasFacilitiesMapper.existsInspectionLine(id);  //判断路线下是否存在设施
                int existsPlan = fasInspectionLineMapper.existsInspectionPlan(id);
                if (existsPlan > 0) {
                    existsIds.add(id);
                } else {
                    dataList.add(id);
                }
            }
        }
        if (existsIds.size() > 0) {
            return AjaxResult.error("线路下存在计划，不能删除，线路编号为：" + StringUtils.join(existsIds, ","));
        }
        int count = 0;
        // 删除路线下没有绑定计划的路线
        if (dataList.size() > 0) {
            Long[] integers = dataList.toArray(new Long[0]);
            count = fasInspectionLineMapper.deleteFasInspectionLine(integers);
            //清空设施对应的路线
            fasFacilitiesMapper.batchDeleteRoute(integers);
        }
        return count > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<FasFacilitiesInspection> findFacility(FasFacilitiesInspection fasFacilitiesInspection) {
        return fasInspectionLineMapper.findFacility(fasFacilitiesInspection);
    }

    /**
     * 查询线路的及线路状态
     *
     * @param userId
     * @param deptId
     * @return
     */
    @Override
    public List<IpqcInspectionLine> miniappIpqcLine(Integer userId, Integer deptId, Integer lineStatus) {
        List<IpqcInspectionLine> listGroup = fasInspectionLineMapper.selectByUserId(userId, deptId, lineStatus);

        List<IpqcInspectionLine> removeData = new ArrayList<>();
        for (IpqcInspectionLine line : listGroup) {
            List<Integer> userList = line.getUserList();
            if (!userList.contains(userId)) {//删除当前路线下没有此用户
                removeData.add(line);
            }
        }
        listGroup.removeAll(removeData);
        return listGroup;
    }

    @Override
    public JSONObject miniappIpqcLineBuilding(Long taskId) {
        List<IpqcLineBuilding> ipqcInspectionLines = fasInspectionLineMapper.miniappIpqcLineBuilding(taskId);
        Map<String, List<IpqcLineBuilding>> map = ipqcInspectionLines.stream().collect(Collectors.groupingBy(IpqcLineBuilding::getBuildingName));

        JSONObject json = new JSONObject();
        List list = new ArrayList(map.size());
        IpqcLineBuilding ipqcLineBuilding = new IpqcLineBuilding();
        for (Map.Entry<String, List<IpqcLineBuilding>> stringListEntry : map.entrySet()) {
            Map<String, Object> resultMap = new HashMap<>();
//            巡检路线状态（0：已完成，1：进行中，2：待开始）
            Integer status = null;
            String key = stringListEntry.getKey();
            List<IpqcLineBuilding> values = stringListEntry.getValue();
            int facilityCompleteNum = 0;
            for (IpqcLineBuilding value : values) {
                // value.getFacilityCompleteStatus() 为1 表示该设施已经检查过，为0 则表示未被检查
                facilityCompleteNum += value.getFacilityCompleteStatus();
            }
            if (facilityCompleteNum == values.size()) {//该建筑下设施全部巡检完成
                status = 0;
            } else if (0 < facilityCompleteNum && facilityCompleteNum < values.size()) {//该建筑下还有为检设施，进行中
                status = 1;
            } else if (facilityCompleteNum == 0) { //该建筑下的设施一个都没开始检查
                status = 2;
            }
            ipqcLineBuilding = values.get(0);
            resultMap.put("buildingName", key);
            resultMap.put("status", status);
            resultMap.put("taskId", String.valueOf(taskId));
            list.add(resultMap);
        }
        if (!Objects.isNull(ipqcLineBuilding)) {
            json.put("headInfo", ipqcLineBuilding);
        }
        json.put("buildingList", list);
        return json;
    }

    @Override
    public List miniappIpqcCenterLine(Integer lineStatus, Integer pageNum, Integer pageSize, Integer orderType, SysUser user) {
        Long userId = user.getUserId();
        Long deptId = user.getDeptId();
        List list = new ArrayList<>();
        List<IpqcInspectionLine> lineList = new ArrayList<>();
        List<IpqcCenterAlarmVo> alarmList = new ArrayList<>();
        if (Objects.isNull(orderType)) {    // 巡检路线和报警路线
            lineList = this.miniappIpqcLine(userId.intValue(), deptId.intValue(),  lineStatus);
            alarmList = fasInspectionLineMapper.getAlarmList(lineStatus, userId);
        } else if (orderType == 0) { // 巡检路线
            lineList = this.miniappIpqcLine(userId.intValue(), deptId.intValue(),  lineStatus);
        } else if (orderType == 2) { // 报警路线
            alarmList = fasInspectionLineMapper.getAlarmList(lineStatus, userId);
        }
        if (!CollectionUtils.isEmpty(alarmList)) {
            alarmList.stream().filter(i -> StringUtils.isNotBlank(i.getSystemId())).forEach(s -> s.setSystemName(DictUtils.getDictLabel("sys_equipment_system", s.getSystemId())));
        }
        list.addAll(lineList);
        list.addAll(alarmList);
        return list;
    }

    @Override
    public List<IpqcLineBuildingFacilityVo> miniappIpqcLineBuildingFacility(Long taskId, String buildingName) {
        return fasInspectionLineMapper.miniappIpqcLineBuildingFacility(taskId, buildingName);
    }

    @Override
    public List<BuildingTreeFacility> searchFacilityListV2(InspectionLineBuildingFacilityVo inspectionLineBuildingFacilityVo) {
        return fasFacilitiesMapper.selectByBuilding(inspectionLineBuildingFacilityVo);
    }

}
